package com.aurora.source.center.activity;

import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.aurora.source.R;
import com.aurora.source.adapter.AddImgAdapter;
import com.aurora.source.base.BaseWhiteToolbarActivity;
import com.aurora.source.center.presenter.AddProductPresenter;
import com.aurora.source.center.view.IAddProductView;
import com.aurora.source.util.DpPxUtil;
import com.aurora.source.util.SPUtils;
import com.aurora.source.widget.ItemDivider;
import com.aurora.source.widget.RecordDialogEditSureCancel;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author: ww
 * @description:添加产品信息
 * @date: 2018/9/7
 */
public class AddProductInformationActivity extends BaseWhiteToolbarActivity<AddProductPresenter> implements IAddProductView {
    private static final int GET_BATCH = 10001;

    AddImgAdapter addImgAdapter;

    String batchNo;
    @BindView(R.id.tv_pre_flow)
    TextView tvPreFlow;
    @BindView(R.id.et_product_name)
    EditText etProductName;
    @BindView(R.id.et_bzq)
    EditText etBzq;
    @BindView(R.id.et_descrip)
    EditText etDescrip;
    @BindView(R.id.rv_add_img)
    RecyclerView rvAddImg;
    @BindView(R.id.et_op_person)
    EditText etOpPerson;
    @BindView(R.id.bt_add)
    AppCompatButton btAdd;
    int maxPic = 5;
    @Override
    public AddProductPresenter attach() {
        return new AddProductPresenter(this);
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_add_product_infomation;
    }

    @Override
    public void initData(@Nullable Bundle bundle) {

    }

    @Override
    public void initView(Bundle savedInstanceState, View contentView) {
        simpleToolbar.setMainTitle("产品信息添加");
        simpleToolbar.setLeftVisibility(View.VISIBLE);
        addImgAdapter = new AddImgAdapter(this);
        rvAddImg.setAdapter(addImgAdapter);
        rvAddImg.setLayoutManager(new GridLayoutManager(this, 4));
        rvAddImg.addItemDecoration(new ItemDivider().setDividerWith(DpPxUtil.dp2px(this, 2)));
        addImgAdapter.setOnAddImgClickListener(new AddImgAdapter.OnAddImgClickListener() {
            @Override
            public void onAddImgClick() {
                if(maxPic-addImgAdapter.getFiles().size()==0){//够了
                    showToast("最多选择5张图片");
                    return;
                }
                showPictureSelector(maxPic-addImgAdapter.getFiles().size(), true);
            }
        });
    }

    @Override
    public void doBusiness() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.tv_pre_flow, R.id.bt_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_pre_flow:
                gotoActivityForResult(BatchSelectActivity.class, GET_BATCH);
                break;
            case R.id.bt_add:
                if (checkNull()) {
                    return;
                }

                final RecordDialogEditSureCancel recordDialogEditSureCancel = new RecordDialogEditSureCancel(activity);
                recordDialogEditSureCancel.setOnSureClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        recordDialogEditSureCancel.dismiss();
                        Map<String, String> params2 = new HashMap<>();
                        params2.put("userId", (String) SPUtils.get(activity, SPUtils.USER_ID, ""));
                        params2.put("batchNo", batchNo);
                        params2.put("productName", etProductName.getText().toString());
                        params2.put("shelfLife", etBzq.getText().toString());
                        params2.put("productContent", etDescrip.getText().toString());
                        params2.put("createUserName", etOpPerson.getText().toString());
                        params2.put("ip", getLocalIpAddress());
                        basePresenter.addProductInfo(params2, addImgAdapter.getFiles());
                    }
                });
                recordDialogEditSureCancel.show();
                break;
        }
    }

    /**     * 获取ip地址     * @return     */
    public  String getHostIP() {
        //获取wifi服务
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        //判断wifi是否开启
        int ipAddress = 0;
        if (wifiManager != null && !wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            ipAddress = wifiInfo.getIpAddress();
        }
        return intToIp(ipAddress);
    }
    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            return "";
        }
        return "";
    }

    private String intToIp(int i) {
        return (i & 0xFF ) + "." +
                ((i >> 8 ) & 0xFF) + "." +
                ((i >> 16 ) & 0xFF) + "." +
                ( i >> 24 & 0xFF) ;
    }


    //非空校验
    private boolean checkNull() {
        if (TextUtils.isEmpty(batchNo)) {
            showToast("请选择上级流程批次");
            return true;
        }

        if (TextUtils.isEmpty(etProductName.getText().toString())) {
            showToast("商品名称为空");
            return true;
        }

        if (TextUtils.isEmpty(etBzq.getText().toString())) {
            showToast("保质期为空");
            return true;
        }

        if (TextUtils.isEmpty(etDescrip.getText().toString())) {
            showToast("商品描述为空");
            return true;
        }

        if (TextUtils.isEmpty(etOpPerson.getText().toString())) {
            showToast("操作人为空");
            return true;
        }

        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case GET_BATCH:
                if (resultCode == RESULT_OK) {
                    tvPreFlow.setText(data.getStringExtra("name"));
                    batchNo = data.getStringExtra("number");
                }
                break;
            case PictureConfig.CHOOSE_REQUEST:
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia e : localMedia) {
                        addImgAdapter.addItem(new File(e.getCutPath()));
                    }
                }
                break;
        }

    }

    @Override
    public void onAddSuccess(String msg) {
        showToast(msg);
        hideSoftInput();
        finish();
    }

    @Override
    public void onAddFail(String msg) {
        showToast(msg);
    }
}
